package iagovsothello.online.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.TreeMap;
import java.util.TreeSet;

public class ServerMain extends Thread {
	
	private ServerWindow serverWindow;
	private int port;
	private TreeMap<String,Record> records;
	
	private boolean running;
	
	public ServerMain(ServerWindow serverWindow, TreeMap<String,Record> records, int port)
	{
		super();
		this.serverWindow = serverWindow;
		this.records = records;
		this.port = port;
		running = false;
	}
	
	public synchronized boolean isRunning() 
	{
		return running;
	}

	public synchronized void setRunning(boolean running) 
	{
		this.running = running;
	}

	public void run()
	{
		setRunning(true);
		ServerSocket serv = null;
		try {
			serv = new ServerSocket(port);
			serv.setSoTimeout(5000);
		} catch (IOException e) {
			serverWindow.getTextAreaLog().append("ERRORE: Impossibile avviare il server\n");
			serverWindow.resetGUI();
		}
		
		if (serv != null)
			serverWindow.getTextAreaLog().append("SERVER AVVIATO\n");
		while(isRunning() && serv != null) 
		{
			try {
				Socket sock = null;
				do {
					try  {
					sock = serv.accept();
					} catch (SocketTimeoutException e) {
						sock = null;
					}
				} while (sock == null && isRunning());
				if (sock != null)
				{
					ServerThread st = new ServerThread(sock,serverWindow,records);
					st.setDaemon(true);
					serverWindow.getTextAreaLog().append("SERVER: connessione accettata\n");
					st.start();
				}
			} catch (IOException e) {
				serverWindow.getTextAreaLog().append("SERVER: tentativo di connessione fallito\n");
			}
		}
		try {
			serv.close();
			serverWindow.getTextAreaLog().append("SERVER SPENTO\n");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
